package com.liuyfly.datastructure;

import com.liuyfly.datastructure.dto.Node;

public class ReversePart<T extends Comparable<T>> {
    public Node<T> reversePart(Node<T> head, int from, int to) {
        int len = 0;
        Node<T> node1 = head;
        Node<T> fPre = null;
        Node<T> tPos = null;
        while (node1!=null){
            len++;
            fPre = len == from-1?node1:fPre;
            tPos = len==to+1?node1:tPos;
            node1= node1.getNext();
        }
        if (from>to||from<1||to>len){
            return head;
        }
        node1 = fPre==null?head:fPre.getNext();
        Node<T> node2 = node1.getNext();
        node1.setNext(tPos);
        Node<T> next;
        while (node2!=tPos){
            next = node2.getNext();
            node2.setNext(node1);
            node1=node2;
            node2=next;
        }
        if (fPre!=null){
            fPre.setNext(node1);
            return head;
        }
        return node1;
    }

}
